package org.mrzc.mvc.control;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.mrzc.mvc.entiy.Course;
import org.mrzc.mvc.listener.ServerPath;
import org.mrzc.mvc.service.CourseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/mvc")
public class MVCControl
{
    @Autowired
    private CourseService mCourseService = null;

    private static Logger mLog = LoggerFactory.getLogger(MVCControl.class);

    @RequestMapping("/hello")
    public String hellowMVC()
    {
        return "hello";
    }

    @RequestMapping("/value")
    public String Value(@RequestParam("Value") String cValue)
    {
        mLog.debug(" Value  = {}", cValue);

        return "hello";
    }

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String showCourse1(@RequestParam("ID") Integer cID, Model cModel)
    {
        mLog.debug(" Course ID = {}", cID);

        Course tCourse = mCourseService.getCoursebyId(cID);
        cModel.addAttribute(tCourse);

        return "course_overview";
    }

    @RequestMapping(value = "/show2/{ID}", method = RequestMethod.GET)
    public String showCourse(@PathVariable("ID") Integer cID, Map<String, Object> cModel)
    {
        mLog.debug(" Course2 ID = {}", cID);

        Course tCourse = mCourseService.getCoursebyId(cID);
        cModel.put("course", tCourse);

        return "course_overview";
    }

    @RequestMapping(value = "/show3", method = RequestMethod.GET)
    public String showCourse(HttpServletRequest cRequest)
    {
        Integer tID = Integer.valueOf(cRequest.getParameter("ID"));

        mLog.debug(" Course3 ID = {}", tID);

        Course tCourse = mCourseService.getCoursebyId(tID);
        cRequest.setAttribute("course", tCourse);

        return "course_overview";
    }

    @RequestMapping(value = "/admin", method = RequestMethod.GET, params = "add")
    public String showAdd()
    {
        return "course_admin/edit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String doSave(@ModelAttribute Course cCourse)
    {
        mLog.debug("doSave = {}", ReflectionToStringBuilder.toString(cCourse));

        cCourse.setCourseId(123);

        // redirect/forward
        return "redirect:show2/" + cCourse.getCourseId();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String showUpload()
    {
        return "course_admin/file";
    }

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String doUpload(@RequestParam("file") MultipartFile cFile) throws IOException
    {
        if (!cFile.isEmpty())
        {
            mLog.debug("doUpload = {}", cFile.getOriginalFilename());

            FileUtils.copyInputStreamToFile(cFile.getInputStream(),
                    new File(ServerPath.getInstance().getRealPath() + File.separator + "upload",
                            System.currentTimeMillis() + cFile.getOriginalFilename()));
        }
        return "success";
    }

    @RequestMapping(value = "/doUpload2", method = RequestMethod.POST)
    public String doUploadFile(MultipartHttpServletRequest multiRequest) throws IOException
    {

        Iterator<String> filesNames = multiRequest.getFileNames();
        while (filesNames.hasNext())
        {
            String fileName = filesNames.next();
            MultipartFile file = multiRequest.getFile(fileName);
            if (!file.isEmpty())
            {
                mLog.debug("Process file: {}", file.getOriginalFilename());
                FileUtils.copyInputStreamToFile(file.getInputStream(),
                        new File(ServerPath.getInstance().getRealPath() + File.separator + "upload",
                                System.currentTimeMillis() + file.getOriginalFilename()));
            }

        }

        return "success";
    }

    @RequestMapping(value = "/{ID}", method = RequestMethod.GET)
    public @ResponseBody Course getCourseInJson(@PathVariable("ID") Integer cID)
    {
        mLog.debug("json = {}", JSON.toJSONString(mCourseService.getCoursebyId(cID)));
        return mCourseService.getCoursebyId(cID);
    }

    @RequestMapping(value = "/jsontype/{courseId}", method = RequestMethod.GET)
    public ResponseEntity<Course> getCourseInJson2(@PathVariable Integer courseId)
    {
        Course tCourse = mCourseService.getCoursebyId(courseId);
        return new ResponseEntity<Course>(tCourse, HttpStatus.OK);
    }

}
